<?php


namespace app\api\service\order;


use app\api\model\MemberType;
use app\api\model\User;
use app\api\service\Token;
use app\api\model\MemberOrder as MemberOrderModel;
use think\Db;
use think\facade\Log;

/**
 * 1. 修改订单状态
 * 2. 修改用户到期时间
 */

class MemberOrderSer extends Token
{
    /**
     * 订单信息
     */
    protected $order;

    /**
     * 用户信息
     */
    protected $user;

    /**
     * 会员卡信息
     */
    protected $memberType;

    /**
     * 入口方法
     */
    public function entrance($order)
    {
        Log::init([
            'type' => 'File'
        ]);
        $this->order = $order;
        $this->user = User::where('openid',$this->order['openid'])->find();
        $this->memberType = MemberType::get($this->order['member_type_id']);
        return $this->judgeOrder();
    }

    /**
     * 判断订单信息
     */
    protected function judgeOrder()
    {
        Db::startTrans();
        try{
            MemberOrderModel::where('id',$this->order['id'])->update([
                'status' => 2,
                'pay_time' => time(),
            ]);
            $this->changeEndTime();
            Db::commit();
            return true;
        } catch (\Exception $e){
            Db::rollback();
            Log::write('会员卡订单回调:'.$e,'error');
            return false;
        }
    }

    /**
     * 修改当前会员的到期时间
     */
    protected function changeEndTime()
    {
        $now_time = time();
        if($this->user['member_end_time']) {
            if($this->user['member_end_time'] > $now_time) {
                $member_end_time = $this->getMemberEndTime($this->user['member_end_time'], $this->memberType['type']);
            }else {
                $member_end_time = $this->getMemberEndTime($now_time, $this->memberType['type']);
            }
        } else {
            $member_end_time = $this->getMemberEndTime($now_time, $this->memberType['type']);
        }
        User::where('openid',$this->user['openid'])->update([
            'member_end_time' => $member_end_time,
            'member_order_id' => $this->order['id'],
            'member_type' => $this->memberType['name']
        ]);
    }

    /**
     * 获取当前会员到期时间
     */
    protected function getMemberEndTime($time,$type)
    {
        if($type == 1) {
            return strtotime("+1date",$time);
        } elseif($type == 2) {
            return strtotime("+1weeks",$time);
        } elseif($type == 3) {
            return strtotime("+1months",$time);
        } elseif($type == 4) {
            return strtotime("+3months",$time);
        } elseif($type == 5) {
            return strtotime("+1years",$time);
        }
    }
}